<?php
	/*创建问题对应的相应测试数据文件*/
	function mkdata($pid,$filename,$input,$OJ_DATA){
		$basedir = "$OJ_DATA/$pid";
		$fp = @fopen($basedir . "/$filename", "w");
		if($fp) {
			fputs($fp, preg_replace( "(\r\n)", "\n", $input ));
			fclose($fp);
		} else {
			echo "Error while opening".$basedir."/$filename ,try [chgrp -R www-data $OJ_DATA] and [chmod -R 771 $OJ_DATA ]<br/>";	
		}
	}
	/*将base64编码的字符串解码并存储为文件*/
	function base64decode2File($savepath, $base64_encoded_file) {
		$fp=fopen($savepath ,"wb");
		fwrite($fp,base64_decode($base64_encoded_file));
		fclose($fp);
	}
	/*Utils Functions*/
	function getImagesTags($content){
		preg_match_all("<[iI][mM][gG][^<>]+[sS][rR][cC]=\"?([^ \"\>]+)/?>",$content,$images);
		return $images;
	}	
	/*Save base64 encoded images generated by summernote as files and replace "src" properties.*/
	function replaceimg($str)
	{
		$offset=0;
		while(($p=strpos($str,"<img ",$offset))!==FALSE)
		{
			$ptagend=strpos($str,">",$p);
			$b64p=strpos($str,"base64",$p);
			if($b64p<$ptagend&&$b64p!==FALSE)
			{
				$ps=strpos($str,"src=",$p);
				$pfn=strpos($str,"data-filename=",$p);
				$pexts=strpos($str,".",$pfn+14);
				$pfne=strpos($str,"\"",$pexts);
				$ext=substr($str,$pexts,$pfne-$pexts);
				$pc=strpos($str,",",$ps);
				$pe=strpos($str,"\"",$pc);
				$b64f=substr($str,$pc+1,$pe-$pc-1);
				$md5=md5($b64f);
				//!!FIXME: to make the current code work, you have to create the imguploads folder manually
				//and symlink it to the admin folder...
				//This should be fixed...
				base64decode2File($GLOBALS['OJ_UPLOAD_DATA'].$md5.$ext,$b64f);
				$str=substr_replace($str,$GLOBALS['OJ_WWW_UPLOAD_PATH'].$md5.$ext,$ps+5,$pe-$ps-5);
			}
			$offset=$p+1;
		}
		return $str;
	}
?>
